package org.wattdepot.gdata.kukuicup.updater.energylasttwentyfourhours;

import it.sauronsoftware.cron4j.Scheduler;
import it.sauronsoftware.cron4j.Task;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.WattDepotService;
import org.wattdepot.gdata.kukuicup.updater.Updater;

/**
 * The updater that kicks off the Cron4J tasks to run once an hour and update the spreadsheets 
 * with the last 24 hours of hourly energy data. 
 * @author Philip Johnson
 *
 */
public class EnergyLastTwentyFourHoursUpdater extends Updater {
  
  /**
   * Creates this updater, initializing the various services. 
   * @param wattDepotService The wattdepot service. 
   * @param gdataService The gdata service.
   * @throws Exception If problems occur initializing these services.  
   */
  public EnergyLastTwentyFourHoursUpdater(WattDepotService wattDepotService, 
      GDataService gdataService) throws Exception {
    super("EnergyLastTwentyFourHours", wattDepotService, gdataService);
  }
  
  /**
   * This task generates a separate TimerTask for each source in the spreadsheet. 
   * Each TimerTask runs every hour at one or more minutes past the hour, 
   * gets the hourly actual and baseline energy usage for the preceding 24 hour period, and 
   * writes it out to the spreadsheet.
   */
  @Override
  public void run() {
    Scheduler scheduler = new Scheduler();
    schedulers.add(scheduler);
    int startMinute = 1;
    for (String sourceName : sourceNames) {
      Task task = new EnergyLastTwentyFourHoursTask(wattDepotService, gdataService, 
          spreadsheetURL, sourceName, isVirtual(sourceName), getRow(sourceName));
      String schedule = startMinute + " * * * *";
      startMinute++;
      System.out.format("Scheduling EnergyLastTwentyFourHours for source: %s at start minute %s%n",
          sourceName, startMinute);
      scheduler.schedule(schedule, task);
    }
    scheduler.start();
  }

}
